package com.itcast.activiti.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.activiti.domain.Department;
import com.itcast.activiti.domain.UserInfo;
import com.itcast.activiti.entity.ActIdPassUser;
import com.itcast.activiti.entity.ActIdUser;
import com.itcast.activiti.mapper.ActIdUserMapper;
import com.itcast.activiti.service.IActIdPassUserService;
import com.itcast.activiti.service.IActIdUserService;
import com.itcast.activiti.utils.ActivitiPage;
import com.itcast.activiti.utils.ApplicationContextHelper;
import com.itcast.msas.sdk.base.support.MsasApiResponse;
import com.itcast.msas.sdk.usr.api.MsasUserApi;
import com.itcast.msas.sdk.usr.domain.MsasUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2020-12-31
 */
@Slf4j
@Service
public class ActIdUserServiceImpl extends ServiceImpl<ActIdUserMapper, ActIdUser> implements IActIdUserService {
    @Autowired
    private IActIdPassUserService iActIdPassUserService;
    @Autowired
    private MsasUserApi msasUserApi;

    private IActIdUserService getService() {
        return ApplicationContextHelper.getBean(this.getClass());
    }

    @Override
    @Cacheable(cacheNames = "USER:USERNAME", key = "'USER:USERNAME:'.concat(#email)", unless = "#result == null")
    public String getUserNameByemail(String email) {
        ActIdUser actIdUser = baseMapper.selectOne(new QueryWrapper<ActIdUser>().lambda().eq(ActIdUser::getEmail, email));
        if (actIdUser == null) {
            return null;
        }
        return actIdUser.getFirst();
    }

    @Override
    public ActivitiPage listActIdUserPage(ActivitiPage activitiPage) {
        JSONObject condition = activitiPage.getCondition();
        QueryWrapper<ActIdUser> queryWrapper = new QueryWrapper();
        String userName = condition.getString("userName");
        if (StringUtils.hasText(userName)) {
            queryWrapper.lambda().like(ActIdUser::getFirst, userName);
        }
        String pinYin = condition.getString("pinYin");
        if (StringUtils.hasText(pinYin)) {
            queryWrapper.lambda().like(ActIdUser::getLast, pinYin);
        }
        String email = condition.getString("email");
        if (StringUtils.hasText(email)) {
            queryWrapper.lambda().like(ActIdUser::getEmail, email);
        }
        String search = condition.getString("search");
        if (StringUtils.hasText(search)) {
            queryWrapper.lambda().like(ActIdUser::getFirst, search).or().like(ActIdUser::getLast, search);
        }
        String userNames = condition.getString("userNames");
        if (StringUtils.hasText(userNames)) {
            List<String> list = Arrays.asList(userNames.split(","));
            queryWrapper.lambda().in(ActIdUser::getEmail, list);
        }
        IPage iPage = baseMapper.selectPage(new Page<>(activitiPage.getCurrent(), activitiPage.getSize()), queryWrapper);
        List<ActIdUser> records = iPage.getRecords();
        List<Map<String, Object>> resultList = new ArrayList<>();
        records.forEach(actIdUser -> {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("userName", actIdUser.getFirst());
            resultMap.put("email", actIdUser.getEmail());
            resultList.add(resultMap);
        });
        activitiPage.setTotal(iPage.getTotal());
        activitiPage.setRecords(resultList);
        return activitiPage;
    }


    @Override
    public UserInfo getUserById(String userId) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setUserName(userId);
        return userInfo;
    }

    @Override
    public List<UserInfo> getUsersByDepartmentId(String departmentId) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId("4");
        userInfo.setUserName("张三");
        List<UserInfo> list = new ArrayList<>();
        list.add(userInfo);
        return list;
    }

    @Override
    public String getUserNameById(String userId) {
        return this.getService().getUserNameByemail(userId);
    }

    @Override
    public UserInfo getDepartmentManager(String departmentId) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId("1");
        userInfo.setUserName("张三");
        return userInfo;
    }

    @Override
    public Department getDepartmentById(String departmentId) {
        Department department = new Department();
        department.setName("部门");
        return department;
    }

    @Override
    public String getDepartmentIdByUserId(String userId) {
        return "2";
    }

    @Override
    public String getParentDepartmentIdById(String departmentId) {
        return "3";
    }

    @Override
    public List<String> getDepartmentsById(String departmentId) {
        return Arrays.asList("1", "2", "3");
    }

    @Override
    public List<UserInfo> getUsersByActIdProcessId(String actIdProcessId, String startUserId) {
        List<UserInfo> list = new ArrayList<>();
        List<ActIdPassUser> actIdPassUsers = iActIdPassUserService.passUserEmailByEmail(Integer.parseInt(actIdProcessId), startUserId);
        actIdPassUsers.forEach(actIdPassUser -> {
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(actIdPassUser.getPassUserEmail());
            userInfo.setUserName(getUserNameByemail(actIdPassUser.getPassUserEmail()));
            list.add(userInfo);
        });
        return list;
    }

    @Override
    public boolean add(ActIdUser actIdUser) {
        Assert.isTrue(!checkEmail(actIdUser.getId(), actIdUser.getEmail()), actIdUser.getEmail() + " is exist");
        if (!StringUtils.hasText(actIdUser.getPwd())) {
            actIdUser.setPwd("123456");
        }
        String email = actIdUser.getEmail();
        actIdUser.setLast(email.substring(0, email.indexOf("@")));
        actIdUser.setTenantId(1);
        int insert = baseMapper.insert(actIdUser);
        return insert == 1;
    }

    private boolean checkEmail(Integer id, String email) {
        Assert.hasText(email, "email is empty");
        ActIdUser actIdUser = baseMapper.selectOne(new QueryWrapper<ActIdUser>().lambda().eq(ActIdUser::getEmail, email));
        if (id == null) {
            return actIdUser != null;
        }
        if (actIdUser == null) {
            return false;
        }
        if (!id.equals(actIdUser.getId()) && actIdUser.getEmail().equals(email)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean del(Integer id, String userId) {
        return baseMapper.deleteById(id) == 1;
    }

    @Override
    public void addUserByEmails(Set<String> userEmails) {
        for (String userEmail : userEmails) {
            ActIdUser actIdUser = baseMapper.selectOne(new QueryWrapper<ActIdUser>().lambda().eq(ActIdUser::getEmail, userEmail));
            if (actIdUser != null) {
                continue;
            }
            MsasApiResponse<MsasUser> res = msasUserApi.userByAccount(userEmail);
            log.info("Worker center response:{}", res);
            Assert.isTrue(res.getCode().equals(MsasApiResponse.OK), "不存在的用户：" + userEmail);
            MsasUser result = res.getResult();
            ActIdUser user = new ActIdUser();
            user.setPwd("123456");
            user.setEmail(userEmail);
            user.setFirst(result.getCn());
            user.setLast(userEmail.substring(0, userEmail.indexOf("@")));
            user.setTenantId(1);
            baseMapper.insert(user);
        }
    }
}
